package main

import (
	"flag"
	"fmt"
	"github.com/kevinburke/ssh_config"
	"os"
	"path/filepath"
	"regexp"
)

var (
	group         = "*" // 组
	env           = "*" // 环境
	hostName      = "*" // 主机名
	sshConfigPath = filepath.Join(os.Getenv("HOME"), ".ssh", "config")
)

func main() {
	flag.StringVar(&group,"group",group,"组")
	flag.StringVar(&env,"env",env,"环境")
	flag.StringVar(&hostName,"hostName",hostName,"主机名")
	flag.StringVar(&sshConfigPath,"sshConfigPath",sshConfigPath,"ssh_config 配置文件路径,默认: ~/.ssh/config")

	flag.Parse()


	f, _ := os.Open(sshConfigPath)
	cfg, _ := ssh_config.Decode(f)
	for _, host := range cfg.Hosts {
		for _, pattern := range host.Patterns {
			//p := fmt.Sprintf("^%s.%s-%s$", group, hostName, env)
			p := fmt.Sprintf("^%s.%s-%s", group, hostName, env)
			//fmt.Println(p)
			isMatch, err := regexp.Match(p, []byte(pattern.String()))
			checkErr(err)
			if isMatch {
				_hostName, err := cfg.Get(pattern.String(), "HostName")
				checkErr(err)
				_user, err := cfg.Get(pattern.String(), "User")
				checkErr(err)
				_port, err := cfg.Get(pattern.String(), "Port")
				checkErr(err)
				fmt.Println(pattern, _hostName, _user, _port)
			}
		}
	}
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}
